package com.sdk.bigdata.client;

import com.alibaba.fastjson.JSONObject;
import com.sdk.bigdata.constant.Constants;
import com.sdk.bigdata.exceptions.DataException;
import com.sdk.bigdata.model.BaseModel;
import com.sdk.bigdata.utils.LoggerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class DataProducer implements Producer {

    private Integer maxSize;
    private Integer maxQueue;
    private Logger logger;
    DataProducer(Integer maxSize, Integer maxQueue) {
        this.maxSize = maxSize;
        this.maxQueue = maxQueue;
        logger = LoggerFactory.getLogger(DataProducer.class);
    }

    /**
     * 发送数据
     *
     * @param message 消息
     * @return DataResponse
     */
    @Override
    public void send(BaseModel message) {
        LoggerUtil.log(logger, Constants.DEBUG, "接收到数据:" + JSONObject.toJSONString(message));
        try {
            message.validAttribute();
        } catch (DataException e) {
            LoggerUtil.log(logger,Constants.ERROR, e.getMessage());
            return;
        }
        if (DataQueue.shutdownFlag) {
            LoggerUtil.log(logger,Constants.ERROR, "服务正在停止，不能继续添加数据");
            return;
        }
        if (DataQueue.getQueue().size() >= maxSize * maxQueue) {
            LoggerUtil.log(logger,Constants.ERROR, "拒绝了请求，目前容器数量过大，不能继续添加");
            return;
        }
        DataQueue.getQueue().offer(message);
    }
}
